package com.pickup.aspect;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.pickup.kafka.provider.KafkaProvider;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


@Aspect
@Component
@Slf4j
@Profile({"dev"})
public class WebLogAspect {

    @Autowired
    private KafkaProvider kafkaProvider;

    // 以自定义 @WebLog 注解为切点
    @Pointcut("@annotation(com.pickup.aspect.WebLog)")
    public void webLog() {
    }

    // 在切点之前织入
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        log.info("切点织入开始..................");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印描述信息
        log.info("Description    : {}", methodDescription);
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        log.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));
    }

    // 在切点之后织入
    @After("webLog()")
    public void doAfter() throws Throwable {
        log.info("切点织入结束..................");
    }

    // 环绕
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("Response Args  : {}", new Gson().toJson(result));
        // 执行耗时
        log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        return result;
    }

    @AfterReturning("webLog()")
    public void doAfterReturning(JoinPoint joinPoint) throws Throwable {
        log.info("返回通知..................");
        sendLog(joinPoint, null);
    }

    @AfterThrowing(value = "webLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) throws Exception {
        log.info("异常通知:  {}", e.getMessage());
        sendLog(joinPoint, e.getMessage());
    }

    public void sendLog(JoinPoint joinPoint, String throwable) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);
        LogMessage logMessage = new LogMessage(
                request.getRequestURL().toString(),
                request.getRemoteAddr(),
                methodDescription,
                request.getMethod(),
                joinPoint.getSignature().getDeclaringTypeName() + joinPoint.getSignature().getName(),
                new Gson().toJson(joinPoint.getArgs()), null, throwable, new Date()
        );
        kafkaProvider.sendChatMsg("logMessage","request.getRemoteAddr()", JSONObject.toJSONString(logMessage));
    }

    // 获取切面注解的描述
    public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazz = method.getParameterTypes();
                if (clazz.length == arguments.length) {
                    description.append(method.getAnnotation(WebLog.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }
}
